<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { showToast } from 'vant';
import { axiosrmedical } from '@/http/axiosRead';
import { useUserStore } from '@/stores/counter';

const router = useRouter();
const userStore = useUserStore();

const patients = ref<{ id: number; name: string; idCard: string; relation: string }[]>([]);
const selectedPatient = ref<{ id: number; name: string; idCard: string; relation: string } | null>(null);
const registerList = ref<{ id: number; department: string; doctorName: string; registerFee: number; patientName: string; appointmentTime: string }[]>([]);
const dateRange = ref<{ start: string; end: string }>({
  start: dayjs().subtract(1, 'year').startOf('day').format('YYYY-MM-DD'),
  end: dayjs().format('YYYY-MM-DD')
});
const showDateRangePicker = ref(false);
const isYearActive = ref(true);
const showPatientPicker = ref(false);

// 日期选择相关
const yearOptions = ['2020', '2021', '2022', '2023', '2024', '2025'];
const monthOptions = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
const dayOptions = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'];

const selectedStartYear = ref(dayjs().subtract(1, 'year').format('YYYY'));
const selectedStartMonth = ref(dayjs().subtract(1, 'year').format('MM'));
const selectedStartDay = ref(dayjs().subtract(1, 'year').format('DD'));

const selectedEndYear = ref(dayjs().format('YYYY'));
const selectedEndMonth = ref(dayjs().format('MM'));
const selectedEndDay = ref(dayjs().format('DD'));

// 当前选择的是开始日期还是结束日期
const isSelectingStart = ref(true);

const maskIdCard = (id: string) => id.replace(/^(.{3}).*(.{4})$/, '$1********$2');
const fetchPatients = async () => {
  try {
    // 初始化时加载用户信息，以防刷新页面
    userStore.loadUserInfo();
    
    // 如果没有accountId，提示用户先登录
    if (!userStore.accountId) {
      showToast('请先登录');
      router.push('/login');
      return;
    }

    const res = await axiosrmedical.get('/Patient/GetPatients', {
      params: { 
        PageIndex: 1, 
        PageSize: 100,
        AccountId: userStore.accountId // 修正参数名为AccountId
      }
    });
    if (res.data.code === 200 && res.data.pageData.length) {
      patients.value = res.data.pageData;
      selectedPatient.value = patients.value[0];
      fetchRegisterList();
    }
  } catch (error) {
    console.error('获取患者列表失败:', error);
    showToast('获取患者列表失败');
  }
};

const fetchRegisterList = async () => {
  if (!selectedPatient.value) return;
  try {
    const res = await axiosrmedical.get('/Register/ShowRegister', {
      params: {
        Status: '已就诊',
        StartDate: dateRange.value.start,
        EndDate: dateRange.value.end,
        SearchName: selectedPatient.value.name,
        PageIndex: 1,
        PageSize: 100,
        AccountId: userStore.accountId // 添加账号ID参数
      }
    });
    if (res.data.code === 200) {
      registerList.value = res.data.pageData;
    }
  } catch (error) {
    console.error('获取挂号记录失败:', error);
    showToast('获取挂号记录失败');
  }
};

const setYear = () => {
  dateRange.value.start = dayjs().subtract(1, 'year').startOf('day').format('YYYY-MM-DD');
  dateRange.value.end = dayjs().format('YYYY-MM-DD');
  isYearActive.value = true;
  fetchRegisterList();
};

const openDatePicker = () => {
  // 初始化日期选择器的值
  selectedStartYear.value = dateRange.value.start.split('-')[0];
  selectedStartMonth.value = dateRange.value.start.split('-')[1];
  selectedStartDay.value = dateRange.value.start.split('-')[2];
  
  selectedEndYear.value = dateRange.value.end.split('-')[0];
  selectedEndMonth.value = dateRange.value.end.split('-')[1];
  selectedEndDay.value = dateRange.value.end.split('-')[2];
  
  isSelectingStart.value = true;
  showDateRangePicker.value = true;
};

const confirmDateRange = () => {
  dateRange.value.start = `${selectedStartYear.value}-${selectedStartMonth.value}-${selectedStartDay.value}`;
  dateRange.value.end = `${selectedEndYear.value}-${selectedEndMonth.value}-${selectedEndDay.value}`;
  isYearActive.value = false;
  showDateRangePicker.value = false;
  fetchRegisterList();
};

const cancelDateRange = () => {
  showDateRangePicker.value = false;
};

// 选择年份
const selectYear = (year: string) => {
  if (isSelectingStart.value) {
    selectedStartYear.value = year;
  } else {
    selectedEndYear.value = year;
  }
};

// 选择月份
const selectMonth = (month: string) => {
  if (isSelectingStart.value) {
    selectedStartMonth.value = month;
  } else {
    selectedEndMonth.value = month;
  }
};

// 选择日
const selectDay = (day: string) => {
  if (isSelectingStart.value) {
    selectedStartDay.value = day;
  } else {
    selectedEndDay.value = day;
  }
};

const openPatientPicker = () => {
  showPatientPicker.value = true;
};

const selectPatient = (patient: { id: number; name: string; idCard: string; relation: string }) => {
  selectedPatient.value = patient;
  showPatientPicker.value = false;
  fetchRegisterList();
};

const goToFeeDetail = (registerId: number) => {
  router.push({ path: '/fee-detail/' + registerId });
};

onMounted(fetchPatients);
</script>

<template>
  <div class="outpatient-fee-page">
    <van-nav-bar
      title="门诊费用"
      left-arrow
      @click-left="router.back()"
      right-text=" "
    >
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>
    <div class="patient-card" v-if="selectedPatient">
      <div class="patient-main">
        <span class="patient-name">{{ selectedPatient.name }}</span>
        <span class="relation">{{ selectedPatient.relation }}</span>
      </div>
      <div class="idcard">{{ maskIdCard(selectedPatient.idCard) }}</div>
      <div class="switch-btn" @click="openPatientPicker">
        切换就诊人
        <span class="switch-icon" @click.stop="openPatientPicker">
          <svg width="20" height="20" viewBox="0 0 20 20"><circle cx="10" cy="10" r="9" stroke="#338aff" stroke-width="2" fill="#fff"/><path d="M7 10l3 3 3-3" stroke="#338aff" stroke-width="2" fill="none" stroke-linecap="round"/></svg>
        </span>
      </div>
    </div>
    <van-popup v-model:show="showPatientPicker" position="bottom" round class="patient-picker-popup">
      <div class="patient-picker">
        <div class="picker-header">
          <span class="picker-title">选择就诊人</span>
          <span class="picker-close" @click="showPatientPicker = false">×</span>
        </div>
        <div class="patient-list">
          <div v-for="p in patients" :key="p.id" class="patient-item" @click="selectPatient(p)">
            <div class="patient-info">
              <span class="patient-name">{{ p.name }}</span>
              <span class="relation">{{ p.relation }}</span>
            </div>
            <div class="idcard">{{ maskIdCard(p.idCard) }}</div>
            <span class="arrow">&gt;</span>
          </div>
        </div>
      </div>
    </van-popup>
    <div class="filter-bar">
      <van-button
        size="small"
        :type="isYearActive ? 'primary' : 'default'"
        @click="setYear"
      >近一年</van-button>
      <van-button
        size="small"
        :type="!isYearActive ? 'primary' : 'default'"
        @click="openDatePicker"
      >选择时间</van-button>
    </div>
    <span class="date-range">{{ dateRange.start }} 至 {{ dateRange.end }}</span>
    <div class="register-list">
      <div v-for="item in registerList" :key="item.id" class="register-card" @click="goToFeeDetail(item.id)">
        <div class="row1">
          <span class="department">{{ item.department }}</span>
          <span class="doctor">{{ item.doctorName }}</span>
          <span class="fee">￥{{ item.registerFee.toFixed(2) }}</span>
        </div>
        <div class="row2">就诊人 {{ item.patientName }}</div>
        <div class="row3">{{ dayjs(item.appointmentTime).format('YYYY-MM-DD HH:mm') }}</div>
      </div>
      <div v-if="registerList.length === 0" class="empty">暂无数据</div>
    </div>
    
    <!-- 日期选择弹窗 -->
    <van-popup v-model:show="showDateRangePicker" position="bottom" round class="date-picker-popup">
      <div class="custom-date-picker">
        <div class="picker-header">
          <div class="cancel-btn" @click="cancelDateRange">取消</div>
          <div class="title">选择时间范围</div>
          <div class="confirm-btn" @click="confirmDateRange">确定</div>
        </div>
        
        <div class="date-range-display">
          <div 
            class="date-input" 
            :class="{ 'active': isSelectingStart }"
            @click="isSelectingStart = true"
          >
            <div class="date-display start-date">
              {{ selectedStartYear }}年{{ selectedStartMonth }}月{{ selectedStartDay }}日
            </div>
          </div>
          <div class="separator">至</div>
          <div 
            class="date-input" 
            :class="{ 'active': !isSelectingStart }"
            @click="isSelectingStart = false"
          >
            <div class="date-display end-date">
              {{ selectedEndYear }}年{{ selectedEndMonth }}月{{ selectedEndDay }}日
            </div>
          </div>
        </div>
        
        <div class="date-selector">
          <div class="year-selector">
            <div 
              v-for="year in yearOptions" 
              :key="year"
              :class="['selector-item', (isSelectingStart ? selectedStartYear : selectedEndYear) === year ? 'active' : '']"
              @click="selectYear(year)"
            >
              {{ year }}
            </div>
          </div>
          <div class="month-selector">
            <div 
              v-for="month in monthOptions" 
              :key="month"
              :class="['selector-item', (isSelectingStart ? selectedStartMonth : selectedEndMonth) === month ? 'active' : '']"
              @click="selectMonth(month)"
            >
              {{ month }}
            </div>
          </div>
          <div class="day-selector">
            <div 
              v-for="day in dayOptions" 
              :key="day"
              :class="['selector-item', (isSelectingStart ? selectedStartDay : selectedEndDay) === day ? 'active' : '']"
              @click="selectDay(day)"
            >
              {{ day }}
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.outpatient-fee-page {
  background: #f8f9fa;
  min-height: 100vh;
}
.patient-card {
  background: #fff;
  border-radius: 10px;
  margin: 16px 12px 12px 12px;
  padding: 16px;
  box-shadow: 0 2px 8px #f0f1f2;
  position: relative;
}
.patient-main {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}
.patient-name {
  font-weight: 600;
  font-size: 16px;
}
.relation {
  background: #e6f0ff;
  color: #338aff;
  border-radius: 8px;
  font-size: 12px;
  padding: 2px 8px;
  margin-left: 8px;
}
.idcard {
  color: #888;
  font-size: 13px;
  margin-bottom: 6px;
}
.switch-btn {
  position: absolute;
  right: 16px;
  top: 16px;
  color: #338aff;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}
.switch-icon {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 12px 12px 12px;
}
.date-range {
  color: #888;
  font-size: 13px;
  margin-left: 12px;
  display: block;
  margin-bottom: 12px;
}
.register-list {
  margin: 0 12px;
}
.register-card {
  background: #fff;
  border-radius: 10px;
  margin-bottom: 14px;
  padding: 14px 16px;
  box-shadow: 0 2px 8px #f0f1f2;
}
.row1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 6px;
}
.department {
  color: #338aff;
}
.doctor {
  margin-left: 10px;
}
.fee {
  color: #e94e77;
  font-weight: bold;
}
.row2, .row3 {
  color: #888;
  font-size: 13px;
  margin-bottom: 2px;
}
.empty {
  text-align: center;
  color: #bbb;
  margin-top: 40px;
}
.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}
.dot {
  width: 6px;
  height: 6px;
  background: #d8d8d8;
  border-radius: 50%;
  display: inline-block;
}
.circle-btn {
  width: 18px;
  height: 18px;
  border: 1.5px solid #d8d8d8;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

/* 日期选择器样式 */
.date-picker-popup {
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
}

.custom-date-picker {
  background: #fff;
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 80vh;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 16px;
  font-weight: 500;
}

.cancel-btn, .confirm-btn {
  padding: 6px 12px;
  font-size: 15px;
}

.cancel-btn {
  color: #666;
}

.confirm-btn {
  color: #338aff;
  font-weight: 500;
}

.date-range-display {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.date-input {
  flex: 1;
  border-radius: 6px;
  cursor: pointer;
  padding: 2px;
}

.date-input.active .date-display {
  background-color: #e6f0ff;
  border: 1px solid #338aff;
}

.separator {
  margin: 0 8px;
  color: #666;
}

.date-display {
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 6px;
  padding: 8px 4px;
  font-size: 14px;
  color: #333;
  border: 1px solid transparent;
  white-space: nowrap;
}

.date-selector {
  display: flex;
  flex: 1;
  overflow: hidden;
  height: calc(80vh - 110px);
  min-height: 200px;
}

.year-selector, .month-selector, .day-selector {
  flex: 1;
  overflow-y: auto;
  text-align: center;
  padding: 8px 0;
  background-color: #fff;
  -webkit-overflow-scrolling: touch;
}

.selector-item {
  padding: 10px 0;
  font-size: 16px;
  color: #333;
}

.selector-item.active {
  color: #338aff;
  font-weight: bold;
  font-size: 18px;
}

.patient-picker-popup {
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
}
.patient-picker {
  background: #fff;
  border-radius: 12px 12px 0 0;
  padding-bottom: 16px;
  width: 100%;
  min-height: 220px;
}
.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px 8px 20px;
  font-size: 18px;
  font-weight: 600;
}
.picker-title {
  flex: 1;
  text-align: center;
}
.picker-close {
  font-size: 22px;
  color: #888;
  cursor: pointer;
}
.patient-list {
  padding: 0 12px;
}
.patient-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}
.patient-info {
  display: flex;
  align-items: center;
  gap: 8px;
}
.patient-item .patient-name {
  font-weight: 600;
  font-size: 16px;
}
.patient-item .relation {
  background: #e6f0ff;
  color: #338aff;
  border-radius: 8px;
  font-size: 12px;
  padding: 2px 8px;
  margin-left: 8px;
}
.patient-item .idcard {
  color: #888;
  font-size: 13px;
  margin-left: 12px;
}
.arrow {
  color: #bbb;
  font-size: 18px;
  margin-left: 8px;
}
</style> 